package com.ruoyi.livedemo.service;

import com.ruoyi.livedemo.dto.PagedResult;
import com.ruoyi.livedemo.dto.QuoteRequest;
import com.ruoyi.livedemo.entity.FavoriteQuote;
import com.ruoyi.livedemo.mapper.FavoriteQuoteMapper;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class QuoteService {

    private final FavoriteQuoteMapper favoriteQuoteMapper;

    public PagedResult<FavoriteQuote> list(Long userId, int page, int size) {
        int pageSize = size <= 0 ? 10 : size;
        int currentPage = Math.max(page, 0);
        int offset = currentPage * pageSize;
        List<FavoriteQuote> items = favoriteQuoteMapper.findPage(userId, offset, pageSize);
        long total = favoriteQuoteMapper.countByUser(userId);
        return new PagedResult<>(total, items);
    }

    @Transactional
    public FavoriteQuote create(Long userId, QuoteRequest request) {
        FavoriteQuote quote = new FavoriteQuote();
        quote.setUserId(userId);
        quote.setContent(request.getContent());
        quote.setSource(request.getSource());
        quote.setMoodTag(request.getMoodTag());
        quote.setCoverPath(request.getCoverPath());
        favoriteQuoteMapper.insert(quote);
        return quote;
    }

    @Transactional
    public FavoriteQuote update(Long userId, Long id, QuoteRequest request) {
        FavoriteQuote quote = new FavoriteQuote();
        quote.setId(id);
        quote.setUserId(userId);
        quote.setContent(request.getContent());
        quote.setSource(request.getSource());
        quote.setMoodTag(request.getMoodTag());
        quote.setCoverPath(request.getCoverPath());
        int rows = favoriteQuoteMapper.update(quote);
        if (rows == 0) {
            throw new IllegalArgumentException("未找到收藏语句");
        }
        return quote;
    }

    @Transactional
    public void delete(Long userId, Long id) {
        favoriteQuoteMapper.delete(id, userId);
    }
}

